package com.prince.web.service.impl;

import com.prince.bean.CommonWebResponse;
import com.prince.bean.ResultParams;
import com.prince.bean.WebCode;
import com.prince.constant.Constants;
import com.prince.mapper.InventoryMapper;
import com.prince.mapper.ProductMapper;
import com.prince.mapper.x.InventoryMapperX;
import com.prince.model.*;
import com.prince.page.Page;
import com.prince.util.*;
import com.prince.web.service.ProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 功能描述: 商品
 * @Author: 王培喜 58528792@163.com
 * @Date: 2021/4/6 15:02
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;
    @Resource
    private InventoryMapper inventoryMapper;
    @Resource
    private InventoryMapperX invenMapperX;
    /**
     * 功能描述: 分页查询商品信息
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 15:25
     */
    @Override
    public Map<String, Object> findProductByPage(Map<String, Object> params, Page page) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria().andDelEqualTo(Constants.YES);
        //封装条件
        if (MapUtil.isNotEmpty(params, "startTime")) {
            Date startTime = DateUtil.strToDate(params.get("startTime").toString(), "yyyy-MM-dd hh:mm:ss");
            Date endTime = DateUtil.strToDate(params.get("endTime").toString(), "yyyy-MM-dd hh:mm:ss");
            criteria.andCreatedBetween(startTime, endTime);
        }
        //单位
        if(MapUtil.isNotEmpty(params,"productUnit")){
            criteria.andProductUnitEqualTo(params.get("productUnit").toString());
        }
        //规格
        if(MapUtil.isNotEmpty(params,"specifications")){
            criteria.andSpecificationsEqualTo(params.get("specifications").toString());
        }
        //供应商
        if(MapUtil.isNotEmpty(params,"supplier")){
            criteria.andSupplierLike("%"+params.get("supplier")+"%");
        }
        //商品名称
        if(MapUtil.isNotEmpty(params,"name")){
            criteria.andNameLike("%"+params.get("name")+"%");
        }
        //查询总数
        int total = productMapper.countByExample(example);
        if (null != page) {
            example.setPage(page);
        }
        example.setOrderByClause("created desc");
        List<Product> list = productMapper.selectByExample(example);
        return response.toHashMapByPage(total,list);
    }
    /**
     * 功能描述: 添加商品信息
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    @Transactional
    public Map<String, Object> addProduct(Product product) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        try {
            //添加数据
            product.setDel(Constants.YES);
            product.setUpdater(product.getCreater());
            product.setCreated(new Date());
            productMapper.insertSelective(product);
            //添加库存
            Inventory it = new Inventory();
            it.setProductId(product.getId());
            it.setDel(product.getDel());
            it.setCreater(product.getCreater());
            it.setCreated(product.getCreated());
            it.setUpdated(product.getCreated());
            it.setUpdater(product.getCreater());
            it.setFirstEnterDate(product.getCreated());
            it.setNumber(new BigDecimal("0.00"));
            String key = Constants.USER + it.getProductId()+it.getNumber();
            it.setMd5key(MD5Util.encryptByMd5AndBASE64(key));
            inventoryMapper.insertSelective(it);
        }catch (Exception e){
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.saveError).toHashMap();
        }
        return response.toHashMap();
    }
    /**
     * 功能描述: 修改商品信息
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> updateProduct(Product product) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        int i = productMapper.updateByPrimaryKeySelective(product);
        if(i < 1){
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.updateError).toHashMap();
        }
        return response.toHashMap();
    }
    /**
     * 功能描述: 删除商品信息
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    @Transactional
    public Map<String, Object> delProduct(Product product) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        try {
            //先查询 库存
            Inventory inventory = invenMapperX.selectByProductId(product.getId());
            if (null != inventory) {
                //有出库记录不能删除
                if (null != inventory.getLastLeaveDate()) {
                    return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.NOT_DELETE).toHashMap();
                }
                //没有出库记录且库存数量不为0
                if (inventory.getNumber().doubleValue() > 0) {
                    return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.RETURN_PRODUCT).toHashMap();
                }
            }
            //删除库存
            inventory.setDel(Constants.NO);
            inventoryMapper.updateByPrimaryKeySelective(inventory);
            //删除商品
            product.setDel(inventory.getDel());
            productMapper.updateByPrimaryKeySelective(product);
        }catch (Exception e){
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.delError).toHashMap();
        }
        return response.toHashMap();
    }
    /**
     * 功能描述: 通过id查询商品
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public Map<String, Object> findProductById(Integer id) {
        ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
        Product product = productMapper.selectByPrimaryKey(id);
        response.put("data",product);
        return response.toHashMap();
    }
    /**
     * 功能描述: 通过拼音码查询商品
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/6 16:02
     */
    @Override
    public List<Map<String,Object>> findProductByPinyin(String pinyin) {
        if(StringUtil.isEmpty(pinyin)){
            return new ArrayList<>();
        }
        List<Map<String,Object>> list =  invenMapperX.selectByProductPinyin("%" + pinyin + "%");
        list.forEach(x->{
            x.put("remark",x.get("name") + "   " + x.get("purchasePrice") + "   " + x.get("number") + "   " + x.get("productUnit")+ "   " + x.get("specifications")+ "   " + x.get("supplier")+ "   " + x.get("pinyin"));
        });
        return list;
    }
}
